package com.atguigu.upp.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.spark.sql.SparkSession;

import java.io.IOException;
import java.io.InputStream;
import java.util.ResourceBundle;

/**
 * Created by Smexy on 2023/3/24
 */
public class UPPUtil
{
    //类似map，快速获取类路径下的properties格式的文件
    static ResourceBundle config = ResourceBundle.getBundle("config");

    //读取配置文件中的参数值
    public static String getValue(String key) {

        String value = config.getString(key);

        return value;

    }

    //检验传入的字符串是否合法
    public static void validParams(String... strs) {

        for (String str : strs) {

            // isBlank(s): 如果s是白字符，返回true 。
            // 白字符:  空格,回车,null, \t,\n
            if (StringUtils.isBlank(str)) {
                throw new RuntimeException("参数非法...");
            }
        }
    }

    //快速基于某个配置文件创建一个SqlSessionFactory
    public static SqlSessionFactory createSqlSessionFactory(String resource) throws IOException {

        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        return sqlSessionFactory;

    }

    //提供方法，创建一个SparkSession
    public static SparkSession getSparkSession(String appName) {

        SparkSession sparkSession = new SparkSession.Builder()
            .appName(appName)
            //设置集群地址 在idea运行，设置为local[*]，打包部署在yarn上，要修改为yarn
            .master(getValue("masterUrl"))
            //设置支持读取hive的元数据
            .enableHiveSupport()
            .getOrCreate();

        return sparkSession;

    }

    public static void main(String[] args) {

        System.out.println(getValue("jdbc.url"));

    }
}
